<template>
  <div>
    <div class="flex h-16 items-center px-5">
      <span class="font-bold">目录</span>
      <span
        v-if="user.name"
        class="flex items-center text-primary ml-4 cursor-pointer"
        @click="handleAdd">
        <!-- <span class="icon iconfont icon-jia"></span> -->
        <img src="@/assets/images/add.png" class="w-4 h-4" />
        新增
      </span>
    </div>
    <draggable v-model:list="list"></draggable>
  </div>
</template>

<script setup lang="ts">
  import { v4 as uuidv4 } from 'uuid'
  import draggable from './draggable.vue'
  import type { ICATALOG } from '@/types'
  import { useCatalogStore, useUserStore } from '@/stores'

  const userStore = useUserStore()
  const user = computed(() => userStore.user)

  const list = ref<Array<ICATALOG>>([])
  const currentCatalog = computed(() => useCatalogStore().catalog)

  function handleAdd() {
    if (currentCatalog.value.isSave === false) {
      return ElMessage.error('请先保存内容')
    }
    const length = list.value.length + 1
    list.value.push({
      name: `目录-${length}`,
      id: uuidv4(),
      children: [],
      isSave: false
    })
    useCatalogStore().setCatalog(list.value[list.value.length - 1])
  }
  const updateList = (list: ICATALOG[]) => {
    list.find((item: ICATALOG) => {
      if (item.isSave === false) {
        item.isSave = true
        return true
      }
      if (item.children && item.children.length > 0) {
        updateList(item.children)
      }
    })
  }
  const exportUpdateList = () => {
    updateList(list.value)
  }
  defineExpose({ exportUpdateList })
</script>

<style scoped></style>
